<template>
	<view class="container">
		<!-- 状态栏占位 -->
		<view class="status-bar"></view>
		
		<!-- 头部区域 -->
		<view class="header">
			<view class="header-content">
				<view class="nav-left" @tap="goBack">
					<image class="back-icon" src="/static/icons/arrow_left.png"></image>
				</view>
				<view class="contact-info">
					<image class="avatar" :src="contact.avatar"></image>
					<view class="info">
						<text class="name">{{ contact.name }}</text>
						<text class="status">{{ contact.online ? '在线' : '离线' }}</text>
					</view>
				</view>
				<view class="nav-right" @tap="showOptions">
					<image class="more-icon" src="/static/icons/more-vertical.png"></image>
				</view>
			</view>
		</view>
		
		<!-- 聊天内容区域 -->
		<scroll-view scroll-y class="chat-content" :scroll-into-view="scrollToMessage" @scrolltoupper="loadMoreMessages" upper-threshold="50">
			<!-- 日期分割线 -->
			<!-- <view class="date-divider" v-for="(dateGroup, date) in groupedMessages" :key="date"> -->
				<!-- <view class="date-label">{{ formatDate(date) }}</view> -->
				
				<!-- 消息列表 -->
				<view class="message-list">
					<view class="message-item"  :class="message.isSelf ? 'right' : 'left'" v-for="(message, index) in messages" :key="index" :id="'msg-' + index">
						<!-- 对方发送的消息 -->
						<view class="message-wrapper left" v-if="!message.isSelf">
							<image class="sender-avatar" :src="contact.avatar"></image>
							<view class="message-content">
								<!-- 文本消息 -->
								<view class="message-bubble" v-if="message.type === 'text'">
									<text class="message-text">{{ message.content }}</text>
								</view>
								
								<!-- 文件消息 -->
								<view class="message-bubble file-message" v-else-if="message.type === 'file'" @tap="previewFile(message)">
									<view class="file-preview">
										<!-- <image class="file-icon" :src="getFileIcon(message.fileType)"></image> -->
										<view class="file-info">
											<text class="file-name">{{ message.fileName }}</text>
											<text class="file-size">{{ message.fileSize }}</text>
										</view>
									</view>
								</view>
								
								<!-- 图片消息 -->
								<view class="message-bubble image-message" v-else-if="message.type === 'image'" @tap="previewImage(message.content)">
									<image class="image-preview" mode="widthFix" :src="message.content"></image>
								</view>
								
								<!-- <text class="message-time">{{ formatTime(message.time) }}</text> -->
							</view>
						</view>
						
						<!-- 自己发送的消息 -->
						<view class="message-wrapper right" v-else>
							<view class="message-content">
								<!-- 文本消息 -->
								<view class="message-bubble self" v-if="message.type === 'text'">
									<text class="message-text">{{ message.content }}</text>
								</view>
								
								<!-- 文件消息 -->
								<view class="message-bubble self file-message" v-else-if="message.type === 'file'" @tap="previewFile(message)">
									<view class="file-preview">
									<!-- 	<image class="file-icon" :src="getFileIcon(message.fileType)"></image> -->
										<view class="file-info">
											<text class="file-name">{{ message.fileName }}</text>
											<text class="file-size">{{ message.fileSize }}</text>
										</view>
									</view>
								</view>
								
								<!-- 图片消息 -->
								<view class="message-bubble self image-message" v-else-if="message.type === 'image'" @tap="previewImage(message.content)">
									<image class="image-preview" mode="widthFix" :src="message.content"></image>
								</view>
								
								<!-- <text class="message-time">{{ formatTime(message.time) }}</text> -->
							</view>
						</view>
					</view>
				</view>
			<!-- </view> -->
		</scroll-view>
		
		<!-- 底部输入区域 -->
		<view class="input-area">
			<view class="input-tools">
				<view class="tool-btn" @tap="showTools">
					<image class="tool-icon" src="/static/icons/plus-circle.png"></image>
				</view>
			</view>
			<view class="input-box">
				<input 
					type="text" 
					v-model="messageText" 
					placeholder="输入消息..." 
					:focus="isInputFocused"
					@focus="onInputFocus"
					@blur="onInputBlur"
					@confirm="sendMessage"
				/>
			</view>
			<view class="send-btn" @tap="sendMessage">
				<image class="send-icon" src="/static/icons/send.png"></image>
			</view>
		</view>
		
		<!-- 工具面板 -->
		<view class="tools-panel" v-if="showToolsPanel">
			<view class="tools-grid">
				<view class="tool-item" @tap="chooseImage">
					<view class="tool-icon-wrapper">
						<image class="tool-icon-large" src="/static/icons/image.png"></image>
					</view>
					<text class="tool-name">图片</text>
				</view>
				<view class="tool-item" @tap="chooseFile">
					<view class="tool-icon-wrapper">
						<image class="tool-icon-large" src="/static/icons/file.png"></image>
					</view>
					<text class="tool-name">文件</text>
				</view>
				<view class="tool-item" @tap="openLocation">
					<view class="tool-icon-wrapper">
						<image class="tool-icon-large" src="/static/icons/map-pin.png"></image>
					</view>
					<text class="tool-name">位置</text>
				</view>
				<view class="tool-item" @tap="startCall">
					<view class="tool-icon-wrapper">
						<image class="tool-icon-large" src="/static/icons/phone.png"></image>
					</view>
					<text class="tool-name">语音通话</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useMainStore } from '@/store'
import { onLoad } from '@dcloudio/uni-app'
const store = useMainStore()



// 响应式数据
const contact = reactive({
  id: '001',
  name: '辽宁工业制造有限公司',
  avatar: '/static/images/a.png',
  online: true
})


const reconnectAttempts = ref(0)
//这是接收对方的消息
const messages = ref([
  {
    id: '1',
    isSelf: false,
	FromUserID: "",
	ToUserID: "",
    type: 'text',
    content: '您好，关于您对我公司工厂自动化设备采购招标的投标，请问贵公司能否提供一下之前的相关经验案例？',
    time: '2023-05-10 10:30',
    date: '2023-05-10',
	 timestamp: Date.now()
  },
  // ...其他消息数据保持不变
])
//这是自己发送的消息

  

messages.value = store.messages
// 修改后（推荐使用计算属性）
//const messages = computed(() => store.messages);

const messageText = ref('')
const touseridx = ref('')
const isInputFocused = ref(false)
const showToolsPanel = ref(true)
const scrollToMessage = ref('')
const isLoading = ref(false)
const socketTask = ref(null)

// 计算属性
const groupedMessages = computed(() => {
  const groups = {}
  messages.value.forEach(message => {
    if (!groups[message.date]) {
      groups[message.date] = []
    }
    groups[message.date].push(message)
  })
  return groups
})
onLoad((option)=>{
	const { id, name, touserid} = option;
	console.log("id:",id,"name:",name,"touseris:",touserid)
	         if(touserid != undefined){
				 
			touseridx.value = touserid	
			 console.log("投标沟通页面：",touseridx.value)
			 }else if(name != undefined){
			touseridx.value = decodeURIComponent(name)
				 console.log('消息列表进来的:', id,touseridx.value ); // 解码 URL 编码的 name
			 }
	    
	  
	  
	 
})
// 生命周期
onMounted((option) => {
 // store.sendMessage({ type: 'ping', content: '测试消息' })
 console.log("页面初次渲染。。")
})

onUnmounted(() => {
  if (socketTask.value && socketTask.value.close) {
    socketTask.value.close(1000, '页面卸载')
  }
})

// 方法函数
// function handleWebSocketMessage(message) {
//   if (message.fromUserID === contact.id) {
//     messages.value.push({
//       ...message,
//       isSelf: false
//     })
//     nextTick(() => scrollToBottom())
//   }
// }

// function keepAlive() {
//   socketTask.value.send({
//     data: JSON.stringify({ type: 'pong' })
//   })
// }

// function reconnect() {
//   if (reconnectAttempts.value > 5) return
//   setTimeout(() => {
//     socketTask.value = uni.connectSocket({ /* 参数 */ })
//     reconnectAttempts.value++
//   }, Math.min(1000 * 2 ** reconnectAttempts.value, 30000))
// }

function loadContactInfo(contactId) {
  console.log('Loading contact info for ID:', contactId)
}

function loadMessages(contactId) {
  console.log('Loading messages for contact ID:', contactId)
}

function loadMoreMessages() {
  if (isLoading.value) return
  isLoading.value = true
  setTimeout(() => {
    isLoading.value = false
  }, 1000)
}

function goBack() {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

function showOptions() {
  uni.showActionSheet({
    itemList: ['查看联系人信息', '清空聊天记录', '投诉举报', '加入黑名单'],
    success: (res) => {
      console.log('Selected option:', res.tapIndex)
    }
  })
}

function sendMessage() {
  // if (!messageText.value.trim()) return
  
  // if (!socketTask.value || socketTask.value.readyState !== 1) {
  //   uni.showToast({ title: '连接未就绪', icon: 'none' })
  //   return
  // }
  
  const consd = uni.getStorageSync("info")
 
   const replyMessage = {
     // id:  parseInt(Date.now().toString()),
     isSelf: true,
     type: 'text',
	 FromUserID: consd.id_card,
	 ToUserID: touseridx.value,
     content: messageText.value,
     time: new Date().toLocaleString(),
     date: new Date().toISOString().split('T')[0]
   }
   messages.value.push(replyMessage)
   
  console.log("消息体：从哪里发",replyMessage.FromUserID,"发去哪里：",replyMessage.ToUserID,"消息体：",replyMessage.content,"时间：",replyMessage.time)

  store.sendMessage(replyMessage)
   messageText.value = ''; // 清空输入框
   scrollToBottom() // 确保DOM更新后滚动
}



function scrollToBottom() {
        nextTick(()=>{
	scrollToMessage.value = 'msg-' + (messages.value.length - 1)		
		})
    
  
}

function onInputFocus() {
  isInputFocused.value = true
  showToolsPanel.value = false
  nextTick(() => scrollToBottom())
}

function onInputBlur() {
  isInputFocused.value = false
}

function showTools() {
  showToolsPanel.value = !showToolsPanel.value
  if (showToolsPanel.value) {
    uni.hideKeyboard()
  }
}

function chooseImage() {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      const imageMessage = {
        id: Date.now().toString(),
        isSelf: true,
        type: 'image',
        content: tempFilePath,
        time: new Date().toLocaleString(),
        date: new Date().toISOString().split('T')[0]
      }
      messages.value.push(imageMessage)
      showToolsPanel.value = false
      nextTick(() => scrollToBottom())
    }
  })
}

function chooseFile() {
  uni.showToast({
    title: '选择文件功能在实际APP中实现',
    icon: 'none'
  })
  
  setTimeout(() => {
    const fileMessage = {
      id: Date.now().toString(),
      isSelf: true,
      type: 'file',
      fileName: '项目方案.docx',
      fileSize: '1.2MB',
      fileType: 'docx',
      content: '/static/files/project-plan.docx',
      time: new Date().toLocaleString(),
      date: new Date().toISOString().split('T')[0]
    }
    messages.value.push(fileMessage)
    showToolsPanel.value = false
    nextTick(() => scrollToBottom())
  }, 500)
}

function openLocation() {
  uni.showToast({
    title: '位置功能在实际APP中实现',
    icon: 'none'
  })
  showToolsPanel.value = false
}

function startCall() {
  uni.showToast({
    title: '通话功能在实际APP中实现',
    icon: 'none'
  })
  showToolsPanel.value = false
}

function previewFile(message) {
  uni.showToast({
    title: `正在打开: ${message.fileName}`,
    icon: 'none'
  })
}

function previewImage(url) {
  uni.previewImage({
    urls: [url],
    current: url
  })
}
</script>
<style scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f7fa;
		display: flex;
		flex-direction: column;
	}
	
	.status-bar {
		height: var(--status-bar-height);
		width: 100%;
		background-color: #1d4ed8;
	}
	
	.header {
		background-color: #1d4ed8;
		padding: 20rpx 30rpx;
	}
	
	.header-content {
		display: flex;
		align-items: center;
	}
	
	.nav-left {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 30rpx;
		margin-right: 20rpx;
	}
	
	.back-icon {
		width: 40rpx;
		height: 40rpx;
	}
	
	.contact-info {
		flex: 1;
		display: flex;
		align-items: center;
	}
	
	.avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 35rpx;
		margin-right: 15rpx;
	}
	
	.info {
		display: flex;
		flex-direction: column;
	}
	
	.name {
		font-size: 32rpx;
		font-weight: 600;
		color: #fff;
	}
	
	.status {
		font-size: 22rpx;
		color: rgba(255, 255, 255, 0.8);
	}
	
	.nav-right {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.more-icon {
		width: 40rpx;
		height: 40rpx;
	}
	
	.chat-content {
		flex: 1;
		padding: 30rpx;
		/* border: 2px solid red; */
		max-width: 650rpx;
		background-color: #f5f7fa;
	}
	
	.date-divider {
		margin-bottom: 30rpx;
	}
	
	.date-label {
		text-align: center;
		font-size: 24rpx;
		color: #999;
		background-color: rgba(0, 0, 0, 0.05);
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		display: inline-block;
		margin: 0 auto 20rpx;
		left: 50%;
		transform: translateX(-50%);
		position: relative;
	}
	
	.message-list {
		display: flex;
		flex-direction: column;
		 width: 100%; /* 新增 */
	}
	
	.message-item {
		margin-bottom: 30rpx;
		
		display: flex;
		width: 100%;
		  
	}
	.message-item.left {
	  justify-content: flex-start; /* 自己消息右对齐 */
	}
	.message-item.right {
	  justify-content: flex-end; /* 自己消息右对齐 */
	}
	
	/* 针对左右消息定义间距 */
	/* .message-item.left .message-bubble {
	  margin-left: 20rpx;   
	}
	
	.message-item.right .message-bubble {
	  margin-right: 20rpx;  
	} */
	
	.message-wrapper {
		display: flex;
		max-width: 80%;
		align-items: flex-end; /* 时间戳对齐底部 */
	}
	
	/* .message-wrapper.left {
		align-self: flex-start;
	}
	
	.message-wrapper.right {
		align-self: flex-end;
		justify-content: flex-end;
		margin-left: auto;
	} */
	
	.sender-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
	}
	
	.message-content {
		display: flex;
		flex-direction: column;
	}
	
	.message-bubble {
		max-width: 70%;
		padding: 20rpx;
		border-radius: 10rpx;
		background-color: #1d4ed8;
        position: relative;		  
	}

	
	.message-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
	}
	
	.message-bubble.self .message-text {
		color: #fff;
	}
	
	.message-time {
		font-size: 22rpx;
		color: #999;
		align-self: flex-end;
		margin-top: 5rpx;
		margin-right: 10rpx;
	}
	
	/* 文件消息样式 */
	.file-message {
		min-width: 400rpx;
	}
	
	.file-preview {
		display: flex;
		align-items: center;
	}
	
	.file-icon {
		width: 60rpx;
		height: 60rpx;
		margin-right: 15rpx;
	}
	
	.file-info {
		display: flex;
		flex-direction: column;
	}
	
	.file-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 5rpx;
		font-weight: 500;
	}
	
	.file-size {
		font-size: 22rpx;
		color: #666;
	}
	
	.message-bubble.self .file-name {
		color: #fff;
	}
	
	.message-bubble.self .file-size {
		color: rgba(255, 255, 255, 0.8);
	}
	
	/* 图片消息样式 */
	.image-message {
		padding: 10rpx;
	}
	
	.image-preview {
		width: 400rpx;
		border-radius: 10rpx;
	}
	
	/* 底部输入区域 */
	.input-area {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		
		position: relative; /* 确保层级上下文 */
		z-index: 999;       /* 提升层级 */
	}
	
	.input-tools {
		margin-right: 20rpx;
	}
	
	.tool-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.tool-icon {
		width: 50rpx;
		height: 50rpx;
		opacity: 0.7;
	}
	
	.input-box {
		flex: 1;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 15rpx 30rpx;
	}
	
	.input-box input {
		width: 100%;
		height: 60rpx;
		font-size: 28rpx;
	}
	
	.send-btn {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background-color: #1d4ed8;
		display: flex;
		
		align-items: center;
		justify-content: center;
		margin-left: 20rpx;
		pointer-events: auto !important; /* 强制启用点击 */
		padding: 10rpx; /* 扩大点击区域 */
		min-width: 100rpx !important; /* 安卓特有尺寸异常 */
	}
	
	.send-icon {
		width: 40rpx;
		height: 40rpx;
	}
	
	/* 工具面板 */
	.tools-panel {
		background-color: #f8f9fa;
		padding: 30rpx;
		border-top: 1px solid #eee;
	}
	
	.tools-grid {
		display: flex;
		flex-wrap: wrap;
	}
	
	.tool-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.tool-icon-wrapper {
		width: 100rpx;
		height: 100rpx;
		background-color: #fff;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 15rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.tool-icon-large {
		width: 50rpx;
		height: 50rpx;
		opacity: 0.8;
	}
	
	.tool-name {
		font-size: 24rpx;
		color: #666;
	}
</style>  